var audio_context;
var recorder;

var time=1;
var timer;
var openUserMedia=false;
var mediaStreamTrack;

var startTime;/*计算录音的开始时间*/
var endTime;/*计算录音的结束时间*/
var recodingTime;/*录音总时长*/
var isRecoding=0;/* 判断当前是否在录音 0=没有录音 1=在录音 */

function __log(e, data) {
    console.log( "\n" + e + " " + (data || ''));
}
function startUserMedia(stream) {
    var input = audio_context.createMediaStreamSource(stream);
     __log('Media stream created.');

    // Uncomment if you want the audio to feedback directly
    input.connect(audio_context.destination);
    __log('Input connected to audio context destination.');

    recorder = new Recorder(input);
     __log('Recorder initialised.');
  }

  function startRecording() {

    recorder.record();

    //解决录音时间问题
    if(isRecoding != 0){
        //如果还在录音直接退出
        return;
    }
      isRecoding = 1;//标识当前正在录音
      startTime = Date.parse(new Date());//获取当前时间
      timer = setInterval("timeOut()",1000);//超过59秒取消录音


    //time=1;
    //timer=setInterval("timeOut()",1000);
    $("#voice_img").hide();
    $("#voice_gif").show();
    // button.disabled = true;
    // button.nextElementSibling.disabled = false;
     __log('Recording...');
  }

  function stopRecording() {

      //获取当前时间

      //解决录音时间不准确问题
      endTime = Date.parse(new Date());
      var recordingTime = Math.ceil((endTime-startTime)/1000);
      recodingTime = recordingTime<1?1:recordingTime>60?60:recordingTime;   //最后录音的时间
      $("#voice").modal("hide");//解决点击多次问题，录完音直接关闭。
      time=1;
      window.clearInterval(timer);


     //window.clearInterval(timer);
     $("#voice_gif").hide();
     $("#voice_img").show();
     // time=1;
    // button.disabled = true;
    // button.previousElementSibling.disabled = false;
    // __log('Stopped recording.');
    mediaStreamTrack && mediaStreamTrack.stop();
    openUserMedia=false;
    // create WAV download link using audio data blob
    createDownloadLink();


    recorder.stop();
    recorder.clear();
  }

  function createDownloadLink() {
    if(myFn.isNil(recorder))
      return;
     recorder.exportWAV(function(blob) {
          var data = new FormData();

                data.append("userId",myData.userId);
                data.append('file', blob);
                data=WEBIM.createOpenApiSecret(data);
                // var xhr = new XMLHttpRequest();
                $.ajax({
                    contentType:"multipart/form-data",
                    type:"POST",
                    url:AppConfig.uploadVoiceUrl,
                    data:data,
                    dataType:"json",
                    processData:false,
                    contentType:false,
                    success:function(result){
                        var msg=WEBIM.createVoiceMessage(3, result["url"],1,recodingTime);
                        UI.sendMsg(msg);

                        isRecoding = 0;//标识当前已录音完毕
                        recodingTime=0;/*当关闭录音窗口才  重置录音时间为零*/
                        // audioData.buffer=[];
                        // audioData.size=0;
                        // context.close();
                    }
                });


    });
  }

function initUserMedia(init) {
  // init  是否 是初始化 加载  false 不是 true 是
    try {
      // webkit shim
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
     navigator.getUserMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia;
     
      
      audio_context = new AudioContext();
       __log('Audio context set up.');
      __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
    } catch (e) {
      //__log(e);
      alert('No web audio support in this browser!');
    }
            navigator.getUserMedia(
                        { audio: true }, //只启用音频

                        function (stream) {
                          $("#voice").modal('show');
                         mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[0];
                          var input = audio_context.createMediaStreamSource(stream);
                               __log('Media stream created.');

                              // Uncomment if you want the audio to feedback directly
                              input.connect(audio_context.destination);
                              __log('Input connected to audio context destination.');
                              
                              recorder = new Recorder(input);
                              openUserMedia=true;
                               __log('Recorder initialised.');
                        }, 
                        function (error) {
                          openUserMedia=false;
                          if(!init)
                            alert('请检查麦克风设备是否连接正常。异常信息:' + (error.code || error.name));
                                   
                        }
            );
                
    
  /*  navigator.getUserMedia({audio: true}, function(stream){
       
     });*/
  };


    function timeOut(){
            if(time<=59){
                ++time;
            }else{
                //暂停录音
                time=1;
                this.stopRecording();
                window.clearInterval(timer);
            }
    };